<template>
  <div
    style="
      min-height: 630px;
      padding: 3px;
      background-color: rgba(255, 255, 255, 1);
    "
  >
    <row>
      <Button
        @click="toRestory()"
        type="primary"
        style="margin-right: 10px"
        v-if="Validation.check(Resources.RESTORE_FACTORY_VIEW)"
      >
        恢复出厂操作记录
      </Button>
      <Button
        icon="ios-add"
        type="primary"
        @click="toAdd()"
        style="margin-right: 10px"
        v-if="Validation.check(Resources.DEVICE_ADD)"
      >
        新增设备
      </Button>
      <Button
        icon="md-download"
        style="margin-right: 5px"
        @click="toImport()"
        v-if="Validation.check(Resources.DEVICE_BATCH_EXCEL)"
        >导入
      </Button>
      <Button
        icon="md-create"
        @click="toEditCategory"
        :disabled="IsEmpty(bloc.deviceSn)"
        style="margin-right: 5px"
        v-if="Validation.check(Resources.DEVICE_BATCH_SORT)"
        >修改分类
      </Button>
      <Button
        icon="ios-trash"
        @click="batchDeleteAction()"
        style="margin-right: 5px"
        v-if="Validation.check(Resources.DEVICE_BATCH_DELETE)"
        >批量删除
      </Button>
      <Button
        icon="md-create"
        @click="toAgentEdit"
        style="margin-right: 5px"
        v-if="Validation.check(Resources.DEVICE_BATCH_AGENT)"
        >修改经销商
      </Button>
    </row>
    <row style="margin-top: 20px" type="flex" justify="start" :gutter="5">
      <col span="24" />
      <Select
        v-model="bloc.model.sortId"
        @on-change="handleChange(bloc.model.sortId)"
        placeholder="全部分类"
        style="width: 180px; margin-right: 10px"
      >
        <Option v-for="item in bloc.sortList" :value="item.id" :key="item.id"
          >{{ item.sortName }}
        </Option>
      </Select>
      <Select
        v-model="bloc.model.modelId"
        placeholder="全部型号"
        style="width: 180px; margin-right: 10px"
      >
        <Option v-for="item in bloc.modelList" :value="item.id" :key="item.id"
          >{{ item.modelName }}
        </Option>
      </Select>
      <Input
        v-model="bloc.model.deviceSn"
        style="width: 180px; margin-right: 10px"
        placeholder="设备编号"
      ></Input>
      <CompanySeletorSingle
        :companyId="bloc.model.companyId"
        style="width: 180px; margin-right: 10px"
        @on-change="(value) => companyChange(value)"
        v-if="tepee === '1'"
      ></CompanySeletorSingle>
      <AgentSelector
        :agentId="bloc.model.agentId"
        :tagCount="1"
        style="width: 180px; margin-right: 10px"
        :agents="bloc.agentList"
        @on-change="(value) => (bloc.model.agentId = value)"
        v-if="tepee === '1'"
      ></AgentSelector>
      <al-cascader
        level="1"
        v-model="resItems"
        style="width: 180px; margin-right: 10px"
        @on-change="getArea"
        ref="address"
        placeholder="全国"
      />
      <Select
        v-model="bloc.model.statusCode"
        style="width: 180px; margin-right: 10px"
        placeholder="设备状态"
        clearable
      >
        <Option
          v-for="(item, index) in deviceStatusListParam"
          :value="index"
          :key="index"
          >{{ item }}</Option
        >
      </Select>
      <!--      <Select v-model="bloc.model.firmwareVersions" style=" width: 180px;margin-right:10px" placeholder="固件版本"-->
      <!--              clearable>-->
      <!--        <Option v-for="(item,index) in bloc.firmwareVersions" :value="item" :key="index">{{ item }}</Option>-->
      <!--      </Select>-->
      <!--      <Select v-model="bloc.model.softwareVersions" style=" width: 180px;margin-right:10px" placeholder="插件版本"-->
      <!--              clearable>-->
      <!--        <Option v-for="(item,index) in bloc.pluginVersions" :value="item" :key="index">{{ item }}</Option>-->
      <!--      </Select>-->
      <Button
        icon="ios-search"
        type="primary"
        style="margin-right: 5px"
        @click="bloc.getDevice(1, bloc.DevVo.pageSize, 'DESC', bloc.model)"
        >查询
      </Button>
      <Button icon="md-refresh" @click="reset">重置 </Button>
      <!--      </col>-->
    </row>
    <div style="margin-top: 20px">
      共 {{ bloc.DevVo.itemCount }} 台
      </div>
    <div style="margin-top: 20px">
      <Table
        border
        ref="selection"
        :columns="columns4"
        :data="bloc.DevVo.items"
        @on-selection-change="tableSelet"
      >
        <template slot-scope="{ row }" slot="status">
          <span :class="row.statusCode === 'ERROR' ? 'red' : 'blue'">{{
            deviceStatusListParam[row.statusCode]
          }}</span>
        </template>
        <template slot-scope="{ row }" slot="action">
          <div style="white-space: nowrap">
            <Button
              size="small"
              @click="openModel2(row)"
              type="warning"
              v-if="Validation.check(Resources.RESTORE_FACTORY_VIEW)"
            >
              恢复出厂
            </Button>
            <Button
              size="small"
              @click="toModifyItem(row.id)"
              type="info"
              v-if="Validation.check(Resources.DEVICE_UPDATE)"
            >
              编辑
            </Button>
            <Button
              size="small"
              type="info"
              @click="toDetail(row)"
              v-if="Validation.check(Resources.DEVICE)"
              >详情
            </Button>
            <Button
              size="small"
              @click="toRemoveItem(row)"
              type="warning"
              v-if="Validation.check(Resources.DEVICE_DELETE)"
            >
              删除
            </Button>
          </div>
        </template>
        <slot name="footer" slot="footer">
          <Page
            show-elevator
            show-total
            show-sizer
            :total="bloc.DevVo.itemCount"
            :current="bloc.DevVo.pageIndex"
            :page-size="bloc.DevVo.pageSize"
            :page-size-opts="[15, 30, 50, 100]"
            @on-change="
              (val) => bloc.getDevice(val, bloc.DevVo.pageSize, 'DESC')
            "
            @on-page-size-change="
              (val) => {
                bloc.DevVo.pageSize = val;
                bloc.getDevice(1, bloc.DevVo.pageSize, 'DESC');
              }
            "
          />
        </slot>
      </Table>
    </div>

    <Modal
      title="经销商修改"
      v-model="agentEdit"
      class-name="vertical-center-modal"
    >
      <div>
        <Form :model="bloc.agentEdit" label-position="right" :label-width="100">
          <FormItem label="经销商修改:" style="margin-bottom: 0px">
            <AgentSelectorSingle
              :agentId="bloc.agentEdit.agentId"
              :tagCount="1"
              style="margin-right: 5px"
              @on-change="(value) => (bloc.agentEdit.agentId = value)"
            ></AgentSelectorSingle>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          :loading="btnload.loading"
          @click="PutDeviceBatchAgent(bloc.agentEdit.agentId, bloc.deviceSn)"
          >确定
        </Button>
      </div>
    </Modal>

    <Modal
      title="修改分类"
      v-model="editCategory"
      class-name="vertical-center-modal"
      @on-cancel="cancel"
    >
      <p slot="header">
        <span>修改分类</span>
      </p>
      <div>
        <Form
          :model="model"
          label-position="right"
          :label-width="100"
          ref="formValidateEditSort"
          :rules="ruleValidateEditSort"
        >
          <FormItem label="设备分类" prop="sortId">
            <Select
              v-model="model.sortId"
              @on-change="handleChange(model.sortId)"
              style="width: 350px; float: left"
            >
              <Option
                v-for="item in bloc.sortList"
                :value="item.id"
                :key="item.id"
                >{{ item.sortName }}
              </Option>
            </Select>
          </FormItem>

          <FormItem label="设备型号" prop="modelId">
            <Select v-model="model.modelId" style="width: 350px; float: left">
              <Option
                v-for="item in bloc.modelList"
                :value="item.id"
                :key="item.id"
                >{{ item.modelName }}
              </Option>
            </Select>
          </FormItem>
        </Form>
      </div>
      <div slot="footer">
        <Button
          type="primary"
          :loading="btnload.loading"
          @click="editSort('formValidateEditSort')"
          >确定</Button
        >
      </div>
    </Modal>

    <Modal v-model="modal2" title="是否清除该设备？" @on-ok="ok2" @on-cancel="cancel2">
      <el-form ref="form" label-width="80px">
        <el-form-item label="型号">
          <el-input v-model="detail.model" readonly=""></el-input>
        </el-form-item>
        <el-form-item label="设备编号">
          <el-input v-model="detail.devicesn" readonly=""></el-input>
        </el-form-item>
      </el-form>
    </Modal>

  </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import { DevicesBloc } from "./DevicesBloc";
import { Route } from "vue-router";
import AgentSelector from "@/component/AgentSelector.vue";
import AgentSelectorSingle from "@/component/AgentSelectorSingle.vue";
import CompanySeletorSingle from "@/component/CompanySeletorSingle.vue";
import { Validation } from "@/base/Validation";
import { Resources } from "@/base/Resources";
import { formatDate } from "@/base/util/Dates";
import { Loading } from "@/base/Loading";
import { isEmpty } from "@/base/util/Strings";
import { store } from "@/store/Store";

@Component({
  components: { AgentSelector, CompanySeletorSingle, AgentSelectorSingle },
})
export default class extends Vue {
  Validation = Validation;
  Resources = Resources;
  IsEmpty = isEmpty;
  @Prop({ type: Number })
  readonly init!: number;
  bloc = new DevicesBloc();
  formDate = formatDate;
  resItems: any = [];
  total: number = 0;
  pageSize: number = 10;
  add: boolean = false;
  edit: boolean = false;
  editCategory: boolean = false;
  agentEdit: Boolean = false;
  show: boolean = false;
  deviceSn: any = "123";
  row: any = {};
  model: any = {
    device: "",
    devNumber: "",
  };
  deviceStatusListParam: any = {
    ONLINE: "在线",
    OFFLINE: "离线",
    AWAIT: "待机",
    WORKING: "使用中",
    ERROR: "故障",
  };
  ruleValidate: any = {
    agentId: [
      {
        required: true,
        message: "经销商不能为空",
        trigger: "change",
        type: "number",
      },
    ],
  };
  ruleValidateEditSort: any = {
    modelId: [
      {
        required: true,
        message: "设备型号不能为空",
        trigger: "blur",
        type: "number",
      },
    ],
    sortId: [
      {
        required: true,
        message: "设备分类不能为空",
        trigger: "blur",
        type: "number",
      },
    ],
  };
  modal2=false;
  detail={
    id:0,
    model:'',
    devicesn:''
  };
  $refs!: {
    formValidateEditSort: HTMLFormElement;
    formValidateEdit: HTMLFormElement;
    selection: HTMLBodyElement;
    address: HTMLFormElement;
  };
  get tepee() {
    if (store.state.user.tepee == "2") {
      //隐藏经销商栏目
      this.columns4 = this.columns4.filter(
        (column) => column.key !== "agentName"
      );
    }
    return store.state.user.tepee;
  }
  companyChange(companyId) {
    this.bloc.model.companyId = companyId;
    this.bloc
      .getAllAngent(this.bloc.angent.pageIndex, 1000, "DESC")
      .then((res) => {})
      .finally(() => {});
  }

  editSort(name) {
    this.$refs[name].validate((valid) => {
      if (valid) {
        this.btnload.loading = true;
        this.bloc
          .PutDeviceBatchSort(
            this.bloc.deviceSn,
            this.model.modelId,
            this.model.sortId
          )
          .then((res) => {
            this.$Message.success("修改分类成功!");
            this.bloc.deviceSn = [];
            this.editCategory = false;
          })
          .catch((res) => {
            this.$Message.error("没有选择需要绑定的设备!");
          })
          .finally(() => {
            this.btnload.loading = false;
          });
      }
    });
  }

  cancel() {
    this.$refs["formValidateEditSort"].resetFields();
  }

  btnload = new Loading();

  PutDeviceBatchAgent(agentId, deviceSn) {
    if (deviceSn.length === 0) {
      this.$Message.error("没有选择需要修改的设备");
      return;
    }
    if (agentId === 0) {
      this.$Message.error("没有选择需要修改的经销商");
      return;
    }
    this.btnload.loading = true;
    this.bloc
      .PutDeviceBatchAgent(agentId, deviceSn)
      .then((res) => {
        this.$Message.success("修改经销商成功!");
      })
      .catch((err) => {
        this.$Message.error(err.message);
      })
      .finally(() => {
        setTimeout(() => {
          this.btnload.loading = false;
        }, 2000);
      });
  }

  columns4: any = [
    {
      type: "selection",
      width: 40,
      align: "left",
    },
    {
      title: "设备分类",
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: this.getSortName(params.row.sortid),
          },
        });
      },
      align: "left",
      width: 100,
      tooltip: true,
    },
    {
      title: "设备型号",
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: this.getModelName(params.row.modelid),
          },
        });
      },
      align: "left",
      width: 150,
      tooltip: true,
    },
    {
      title: "设备图片",
      key: "modelIcon",
      align: "left",
      width: 100,
      render: (h: any, params: any) => {
        return h("div", [
          h("img", {
            domProps: {
              src: params.row.modelIcon,
            },
            style: {
              width: "50px",
              height: "50px",
            },
          }),
        ]);
      },
      tooltip: true,
    },
    {
      title: "颜色",
      key: "colour",
      align: "left",
      width: 180,
      tooltip: true,
    },
    {
      title: "序列号",
      key: "massageSn",
      align: "left",
      width: 180,
      tooltip: true,
    },
    {
      title: "设备编号",
      key: "devicesn",
      align: "left",
      width: 180,
      tooltip: true,
    },
    // {
    //   title: '所属品牌商',
    //   render: (h: any, params: any) => {
    //     return h('span', {
    //       domProps: {
    //         innerText: this.getCompanyName(params.row.companyid)
    //       }
    //     });
    //   },
    //   align: 'left',
    //   minWidth: 200,
    //   tooltip: true
    // },
    {
      title: "所属地区",
      align: "left",
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: Validation.check(Resources.COMPANY_SPECIFIC_VIEW)
              ? params.row.province + params.row.city
              : "",
          },
        });
      },
      width: Validation.check(Resources.COMPANY_SPECIFIC_VIEW) ? 120 : 0,
      tooltip: true,
    },
    {
      title: "总使用时长/小时",
      key: "totalTime",
      align: "left",
      width: 80,
      tooltip: true,
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: Math.floor(params.row.totalTime / 3600),
          },
        });
      },
    },
    {
      title: "总使用次数",
      key: "totalNum",
      align: "left",
      width: 80,
      tooltip: true,
    },
    {
      title: "设备状态",
      slot: "status",
      width: 80,
      tooltip: true,
      // render: (h: any, params: any) => {
      //   let status = this.deviceStatusList[params.row.status];
      //   return h('span', status);
      // }
    },
    {
      title: "制造商",
      key: "factory",
      align: "left",
      width: 100,
      tooltip: true,
    },
    {
      title: "固件版本",
      align: "left",
      key: "firmwareVersions",
      width: Validation.check(Resources.ACCOUNT_VIEW) ? 80 : 0,
      tooltip: true,
    },
    // {
    //   title: "固件更新时间",
    //   key: "firmwareTime",
    //   align: "left",
    //   width: Validation.check(Resources.ACCOUNT_VIEW)?160:0,
    //   tooltip: true,
    //   render: (h: any, params: any) => {
    //     if (!params.row.firmwareTime) {
    //       return h('span', '');
    //     }
    //     return h('span', {
    //       domProps: {
    //         innerText: formatDate(
    //           new Date(params.row.firmwareTime),
    //           'yyyy-MM-dd hh:mm:ss'
    //         )
    //       }
    //     });
    //   }
    // },
    // {
    //   title: '硬件版本',
    //   align: 'left',
    //   key: 'softwareVersions',
    //   width: 80,
    //   tooltip: true
    // },
    // {
    //   title: "启动页",
    //   key: "startImage",
    //   align: "left",
    //   width: 180,
    //   tooltip: true,
    // },
    // {
    //   title: "更新时间",
    //   key: "updated",
    //   align: "left",
    //   slot: "updated",
    //   width: 160,
    //   tooltip: true,
    //   render: (h: any, params: any) => {
    //     return h('span', {
    //       domProps: {
    //         innerText: formatDate(
    //           new Date(params.row.updated),
    //           'yyyy-MM-dd hh:mm:ss'
    //         )
    //       }
    //     });
    //   }
    // },
    {
      title: "最近使用时间",
      key: "statusupdatetime",
      align: "left",
      width: 160,
      tooltip: true,
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: formatDate(
              new Date(params.row.statusupdatetime),
              "yyyy-MM-dd hh:mm:ss"
            ),
          },
        });
      },
    },
    {
      title: "添加时间",
      key: "created",
      align: "left",
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: formatDate(
              new Date(params.row.created),
              "yyyy-MM-dd hh:mm:ss"
            ),
          },
        });
      },
      width: 160,
      tooltip: true,
    },
    {
      title: "所属经销商",
      key: "agentName",
      align: "left",
      width: 200,
      tooltip: true,
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText:
              params.row.agentid > 0
                ? "ID:" + params.row.agentid + "\n" + params.row.agentName
                : "",
          },
        });
      },
    },
    {
      title: "激活状态",
      key: "activeState",
      align: "left",
      width: 200,
      tooltip: true,
      render: (h: any, params: any) => {
        return h("span", {
          domProps: {
            innerText: params.row.activeState == 1 ? "激活" : "未激活",
          },
        });
      },
    },
    {
      title: "操作",
      key: "action",
      align: "left",
      width: 47 * 4 + 50,
      fixed: "right",
      slot: "action",
    },
  ];

  getSortName(sortId) {
    return this.bloc.getSortName(sortId);
  }

  getModelName(modelid) {
    return this.bloc.getModelName(modelid);
  }

  getCompanyName(companyid) {
    return this.bloc.getCompanyName(companyid);
  }

  toAdd() {
    this.$router.push({ path: "/device-manage/add" });
  }
  toRestory() {
    this.$router.push({ path: "/device-manage/restory" });
  }

  toAgentEdit() {
    this.agentEdit = true;
    this.bloc
      .getAllAngent(this.bloc.angent.pageIndex, 1000, "DESC")
      .then((res) => {})
      .finally(() => {});
  }

  filterMethod(value, option) {
    return option.agentName.indexOf(value) !== -1;
  }

  getArea(data) {
    if (data.length > 0) {
      this.bloc.model.provinceId = data[0].code;
      this.bloc.model.province = data[0].name;
      if (data.length > 1) {
        this.bloc.model.cityId = data[1].code;
        this.bloc.model.city = data[1].name;
      }
    }
  }

  handleChange(sortId) {
    this.bloc
      .getAllModel(this.bloc.angent.pageIndex, 1000, sortId, "DESC", undefined)
      .then((res) => {});
  }

  batchDeleteAction() {
    this.$Modal.confirm({
      title: "提示",
      content: "确认删除后将无法恢复！还要继续吗？",
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        this.bloc
          .PutDeviceBatchDelete(this.bloc.deviceSn)
          .then((res) => {
            if (res.name === "") {
              this.$Message.success("批量删除设备成功");
            } else {
              this.$Message.error("批量删除设备失败");
            }
          })
          .catch((res) => {
            this.$Message.error("请选择设备");
          });
      },
    });
  }

  toModifyItem(id) {
    // 记录查询条件
    sessionStorage.setItem('data',JSON.stringify(this.bloc.model))
    sessionStorage.setItem('isshow', 'true')
    this.$router.push({
      path: "/device-manage/edit/" + id,
    });
  }

  toDetail(row) {
    sessionStorage.setItem("data",JSON.stringify(this.bloc.model))
    sessionStorage.setItem('isshow', 'true')
    this.$router.push({
      path: "/device/detail/" + row.id,
      query: {
        data: row.devicesn,
        fenlei: this.getSortName(row.sortid),
        shoper:  row.agentid > 0
                ? row.agentName
                : "",
        address:row.province + row.city,
        color: row.colour,
        xinghao:this.getModelName(row.modelid)
      },
    });
  }
  mounted() {
    if(!sessionStorage.getItem('isshow')) return
      // this.bloc.model =  JSON.parse(sessionStorage.getItem('data')) 
    
  }

  toRemoveItem(row) {
    this.$Modal.confirm({
      title: "提示",
      content: "确认删除后将无法恢复！还要继续吗？",
      okText: "删除",
      cancelText: "取消",
      onOk: () => {
        this.bloc.removeItem(row).then((res) => {
          if (res.name === "") {
            this.$Message.success("设备删除成功");
          } else {
            this.$Message.error("设备删除失败");
          }
        });
      },
    });
  }

  toImport() {
    this.$router.push({ path: "/device/import" });
  }

  @Watch("edit")
  nameChanged(newVal: string, oldVal: string) {}

  tableSelet(selection) {
    this.bloc.deviceSn = selection.map((item) => {
      return item.id;
    });
  }

  toEditCategory() {
    this.editCategory = true;
    this.bloc.getAllAngent(this.bloc.angent.pageIndex, 1000, "DESC");
    this.bloc.getAllSort(this.bloc.angent.pageIndex, 1000, "DESC");
  }

  beforeRouteEnter(to: Route, from: Route, next: (vm: any) => void) {
    next((vm) => {
      vm.bloc
        .getCompanyList(vm.bloc.DevVo.pageIndex, vm.bloc.DevVo.pageSize, "DESC")
        .catch((e) => {
          vm.$Message.error("操作错误");
        });
      vm.bloc.getAllAngent(1, 1000, "DESC");
      vm.bloc.getAllSort(1, 1000, "DESC");
      vm.bloc.getAllModel(1, 1000, undefined, "DESC", undefined).then((res) => {
        vm.bloc.modelListAll = res;
      });
      vm.bloc.getDevice(
        vm.bloc.DevVo.pageIndex,
        vm.bloc.DevVo.pageSize,
        "DESC",
        vm.bloc.model
      );
      vm.bloc.getfirmware();
      vm.bloc.getPlugin();
    });
  }

  reset() {
    sessionStorage.clear()
    this.bloc.model = {
      agentId: 0 || undefined,
      city: "",
      cityId: "",
      companyId: undefined,
      deviceSn: "",
      startImage: "",
      modelId: undefined,
      province: "",
      provinceId: "",
      sortId: undefined,
      createBegin: "",
      statusCode: "",
      sortDirection: "DESC",
      modelName: "",
    };
    this.$refs.address.select = [];
    this.bloc.getDevice(
      this.bloc.DevVo.pageIndex,
      this.bloc.DevVo.pageSize,
      "DESC",
      this.bloc.model
    );
  }

  ok2() {
    // 确定恢复出厂
    console.log('恢复出厂');
    
    this.bloc.restoreFactorySettings(this.detail.id);
  }
  // 修改 取消
  cancel2() {
    this.modal2 = false;
  }
  openModel2(info){
    this.detail={
      id:info.id,
      model:this.getModelName(info.modelid),
      devicesn:info.devicesn,
    }
    this.modal2 = true
    console.log(info)
  }

}
</script>
<style lang="less" scoped>
.blue {
  color: #559df9;
}

/deep/ .ivu-form-item-error-tip {
  padding-top: 38px;
}

.red {
  color: red;
}
</style>
